import os
import re
import chardet
import codecs
import requests
import ssl

context = ssl.create_default_context()
context.options &= ssl.OP_NO_TLSv1
context.options &= ssl.OP_NO_TLSv1_1

def submit_form(url, form_data, files=None, headers=None):
    # 创建一个 session 对象
    with requests.Session() as session:
        # 如果提供了自定义 headers，则更新 session 的 headers
        if headers:
            session.headers.update(headers)

        # 发送 POST 请求
        response = session.post(url, data=form_data, files=files, verify=False)

        # 返回响应对象

def detect_and_convert_file(file_path):
    # 检测文件的字符集
    if os.path.exists(file_path + ".ig"):
        return
    print(f"检测字符集 {file_path}")
    with open(file_path, 'rb') as file:
        raw_data = file.read(10240)
        result = chardet.detect(raw_data)
        encoding = result['encoding']
        print(encoding, type(encoding))
    if encoding == 'utf-8':
        return
    if encoding == None:
        encoding = "GB2312"
        # 以检测到的字符集读取文件，然后以 UTF-8 格式写入新文件
    with codecs.open(file_path, 'r', encoding=encoding, errors='replace') as file:
        content = file.read()
    with codecs.open(file_path, 'w', encoding='utf-8') as file:
        file.write(content)

    open(file_path + ".ig", "w")


def get_all_files(directory):
    # 使用os.walk遍历文件夹
    for root, dirs, files in os.walk(directory):
        for file in files:
            # 获取文件的完整路径
            yield os.path.join(root, file)


def load_txt_files():
    ret = []
    dir = r"F:\Share\W 网络小说超级大合集 按分类"
    for k, i in enumerate(get_all_files(dir)):
        if(re.match(r'.*\.(txt|TXT)$', i)):
            ret.append(i)
    return ret


def get_file_name(path):
    return path.split("\\")[-1]


def parse_book_info(file_name):
    pattern = r'(.*)作者(:|：)(.*)\.(txt|TXT)'
    if re.search(pattern, file_name):
        match = re.search(r'(.*)作者(:|：)(.*)\.(txt|TXT)', file_name)
        book_name = match.group(1)
        author = match.group(3)
        return book_name, author
    else:
        n = ""
        return file_name.replace(".txt", "").replace(".TXT", ""), "佚名"


def parse_book_category(path):
    path_arr = path.split("\\")
    if path_arr[-1] == "惊悚小说合集（套装共7册）":
        return path_arr[-2]
    if path_arr[-1] == "起点爆款小说":
        return "未分类"
    return path_arr[-1]


def upload_book(book_name, author, book_category, path):
    if os.path.exists(path + ".big1"):
        return
    url = 'http://localhost:5097/Book/UploadBook'  # 替换为实际的提交 URL
    form_data = {
        'Title': book_name,
        'Author': author,
        'Description': book_name + "-" + author,
        'Type': 'TXT',
        'Category': categorys[book_category],  # 假设 Category 是下拉列表中的一个选项的值
        'Status': 'Updating'
    }
    _files = {
        'StoragePath': ('book.txt', open(path, 'rb'))  # 替换为实际的文件路径
    }
    headers = {
        'Cookie': r'.AspNetCore.Antiforgery.TCXyRVPZ2hQ=CfDJ8ADtoO84NKpJkEB-lFItVBjnYnj2wvrUgi3aoIhXR4U2YpQOlXC7UqJz7d8Xhrt9GoEkHrJ52Oh784_cjFKOkv8q79TP9QOQgQWV596V_i4QNAkJ0qnlXjKLPhnGjv6uCafnT6UDzJpEEDGvZ3wYg9U; .AspNetCore.Session=CfDJ8ADtoO84NKpJkEB%2BlFItVBiQGIRkZLxx3kVYkE%2FG9oaglwwYFX%2Bf5NNePcNgBYSkf9eaGl41DziUTfnFMGVrcXv5QlH31lY6VxOKg3%2F6%2FajrCMKoknrLA7ojpZi%2BDD3tvlNrum5F0r4zLziiyisRX2vbtFKTPj2knbj5us8DcoBU'
    }
    print(book_name, path)
    response = submit_form(url, form_data, _files, headers)
    open(path + ".big", "w")
    pass


categorys = {}
categorys["修真文明"] = 16
categorys["古典仙侠"] = 17
categorys["幻想修仙"] = 18
categorys["武侠仙侠"] = 19
categorys["现代修真"] = 20
categorys["神话修真"] = 21
categorys["三国历史"] = 22
categorys["外国历史"] = 23
categorys["宋朝历史"] = 24
categorys["明朝历史"] = 25
categorys["架空历史"] = 26
categorys["另类幻想"] = 27
categorys["史诗奇幻"] = 28
categorys["异世大陆"] = 29
categorys["黑色幻想"] = 30
categorys["原生幻想"] = 31
categorys["东方玄幻"] = 32
categorys["时空穿梭"] = 33
categorys["超级科技"] = 34
categorys["进化变异"] = 35
categorys["商场职场"] = 36
categorys["娱乐明星"] = 37
categorys["异术超能"] = 38
categorys["都市异能"] = 39
categorys["都市生活"] = 40
categorys["恐怖惊悚"] = 41
categorys["未分类"] = 42

files = load_txt_files()
for i in files:
    file_name = get_file_name(i)
    book_name, author = parse_book_info(file_name)
    category = parse_book_category(os.path.dirname(i))
    upload_book(book_name, author, category, i)
